<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['生产管理', '补料单']" marginBottom="10px" currentMenu="申请补料"></crumbs>
    <div class="form-body">
      <div class="cards-box">
        <a-card title="基本信息" :bordered="false">
          <a-form-model layout="vertical" ref="ruleForm1" :model="requistionForm" :rules="rules">
            <a-form-model-item label="工单编号" required prop="orderId">
              <!-- <a-select placeholder="请选择" v-model="requistionForm.orderId" :disabled="disabled" allowClear @select="selectOrder">
                <a-select-option v-for="o in orderList" :key="o.id" :value="o.id">{{ o.orderCode }}</a-select-option>
              </a-select> -->
              <a-input
                @click="openIt"
                v-model="requistionForm.orderCode"
                placeholder="请选择"
                :read-only="true"
                :class="requistionForm.orderCode ? 'has-value' : ''"
              >
                <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                <a-icon
                  slot="suffix"
                  type="close-circle"
                  theme="filled"
                  class="close-icon"
                  @click="getSelectValue(false, '', [])"
                />
              </a-input>
            </a-form-model-item>
            <a-form-model-item label="生产产品">
              <a-input placeholder="-" disabled v-model="requistionForm.goodsName" />
            </a-form-model-item>
            <a-form-model-item />
          </a-form-model>
          <a-form-model layout="vertical" ref="ruleForm2" :model="requistionForm" :rules="rules">
            <a-form-model-item label="补料人" required prop="reciver">
              <j-select-user-by-dep
                @changeRow="userFilter"
                v-model="requistionForm.reciver"
                :seldep="true"
                :modalWidth="1000"
                :multi="false"
              ></j-select-user-by-dep>
            </a-form-model-item>
            <a-form-model-item label="基本单位">
              <a-input placeholder="-" disabled v-model="requistionForm.goodsBasicUnitText" />
            </a-form-model-item>
            <a-form-model-item />
          </a-form-model>
          <a-form-model layout="vertical" ref="ruleForm" :model="requistionForm" :rules="rules">
            <a-form-model-item label="领用时间">
              <a-date-picker
                format="YYYY-MM-DD HH:mm"
                :show-time="{ defaultValue: moment('00:00', 'HH:mm') }"
                style="width: 100%"
                @change="changeDate"
              />
            </a-form-model-item>
            <a-form-model-item />
            <a-form-model-item />
          </a-form-model>
          <a-form-model layout="vertical" ref="ruleForm3" :model="requistionForm" :rules="rules">
            <a-form-model-item label="补料原因" required prop="reason" style="width: 65%">
              <a-textarea placeholder="请输入" :maxLength="500" v-model="requistionForm.reason" />
            </a-form-model-item>
            <a-form-model-item />
          </a-form-model>
        </a-card>
        <a-card title="领用物料" :bordered="false" style="margin-top: 12px">
          <j-editable-table
            ref="materialTable"
            :loading="goodsTable.loading"
            :columns="goodsTable.columns"
            :dataSource="goodsTable.dataSource"
            :maxHeight="300"
            :rowNumber="false"
            :actionButton="false"
            :rowSelection="true"
            :addActionButton="false"
            @selectRowChange="selectRowChange"
          >
            <template v-slot:action="props">
              <a-popconfirm title="是否删除?" ok-text="是" cancel-text="否" @confirm="handleDeleteGood(props)">
                <span class="del-text">删除</span>
              </a-popconfirm>
            </template>
            <template v-slot:num="props">
              <a-input :maxLength="20" v-model="props.value" placeholder="请输入" @input="(e) => inputNum(e, props)"></a-input>
            </template>
            <template v-slot:planTotalNum="props">
              {{ numFormat(props.value) }}
            </template>
            <template v-slot:onlyReceivedNum="props">
              {{ numFormat(props.value) }}
            </template>
            <template v-slot:lockNum="props">
              {{ numFormat(props.value) }}
            </template>
          </j-editable-table>
        </a-card>
        <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
          <a-form-model layout="vertical">
            <a-form-model-item label="备注" style="flex: 1">
              <a-textarea placeholder="请输入" :maxLength="500" v-model="requistionForm.remark" auto-size />
            </a-form-model-item>
          </a-form-model>
          <a-form-model layout="vertical">
            <a-form-model-item label="附件" style="flex: 1">
              <file-upload :ids="requistionForm.attachment" @getFileList="getFileList"></file-upload>
              <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
            </a-form-model-item>
          </a-form-model>
        </a-card>
        <div style="margin-top: 12px">
          <Examine @submitProcess="submitProcess" type="0" id="MESS_REMEDY_MATERIAL_APPLY" ref="examine" />
          <div style="height: 50px"></div>
        </div>
      </div>
    </div>

    <div class="footer-submit form-footer">
      <a-button type="primary" @click="submitProcess" :loading="submitLoading"> 提交 </a-button>
    </div>
    <tableSelect ref="tableSelect" @getSelectValue="getSelectValue" :key="indexNumber">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
            <a-form-model-item label="工单编号">
              <a-input v-model="filterForm.orderCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="产品名称">
              <a-input v-model="filterForm.goodsName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="searchNumber()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetNumber">重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </tableSelect>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import moment from 'dayjs'
import { fourFloatNum, validateDuplicateValue, numFormat } from '@/utils/util'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { productOrderList } from '@/api/productOrder'
import tableSelect from '@/components/tableSelect'
import Examine from '@/components/examine'
export default {
  data() {
    return {
      jkeForm: {
        title: '申请补料',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      //下拉改弹窗
      indexNumber: 0,
      columns: [
        {
          title: '工单编号',
          ellipsis: true,
          width: 180,
          dataIndex: 'orderCode',
        },
        {
          title: '产品名称',
          width: 120,
          ellipsis: true,
          dataIndex: 'goodsName',
        },
        {
          title: '规格',
          width: 120,
          ellipsis: true,
          dataIndex: 'goodsSpec',
        },
        {
          title: '基本单位',
          dataIndex: 'goodsBasicUnitText',
          ellipsis: true,
          width: 90,
        },
        {
          title: '负责人',
          dataIndex: 'principalName',
          width: 100,
          ellipsis: true,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 180,
          ellipsis: true,
        },
      ],
      numberValue: '',
      numberText: '',
      filterForm: {
        orderCode: '', //工单编号
        goodsName: '', //产品名称
      },
      //下拉改弹窗结束
      numFormat,
      moment,
      validateDuplicateValue,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
      pageTitle: '新建设备',
      submitApi: API.messDeviceAdd,
      isEdit: false,
      queryId: '',
      requistionForm: {
        attachment: '',
        remedyId: '',
        orderId: '',
        goodsName: '',
        orderCode: '',
        goodsBasicUnitText: '',
      },
      submitLoading: false, // 提交loading
      orderList: [],
      rules: {
        orderId: [{ required: true, message: '工单编号必填', trigger: 'change' }],
        reciver: [{ required: true, message: '领料人必填', trigger: 'change' }],
        reason: [{ required: true, message: '补料原因必填', trigger: 'change' }],
      },
      goodsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料',
            width: '10%',
            key: 'goodsName',
            type: FormTypes.normal,
          },
          {
            title: '规格',
            width: '10%',
            key: 'goodsSpec',
            type: FormTypes.normal,
          },
          {
            title: '物料类型',
            width: '10%',
            key: 'goodsTypeText',
            type: FormTypes.normal,
          },
          {
            title: '基本单位',
            width: '10%',
            key: 'goodsBasicUnitText',
            type: FormTypes.normal,
          },
          {
            title: '计划投料总量',
            width: '15%',
            key: 'planTotalNum',
            type: FormTypes.slot,
            slotName: 'planTotalNum',
          },
          {
            title: '净领用量',
            width: '10%',
            key: 'onlyReceivedNum',
            type: FormTypes.slot,
            slotName: 'onlyReceivedNum',
          },
          {
            title: '在申补量',
            width: '10%',
            key: 'lockNum',
            type: FormTypes.slot,
            slotName: 'lockNum',
          },
          {
            title: '退料量',
            key: 'returnNum',
            type: FormTypes.hidden,
          },
          {
            title: '商品编号',
            key: 'goodsCode',
            type: FormTypes.hidden,
          },
          {
            title: '商品Id',
            key: 'goodsId',
            type: FormTypes.hidden,
          },
          {
            title: '计划投料Id',
            key: 'planId',
            type: FormTypes.hidden,
          },
          {
            title: '本次补料量',
            width: '15%',
            key: 'num',
            type: FormTypes.slot,
            isrequired: true,
            placeholder: '请输入${title}',
            slotName: 'num',
            defaultValue: '',
            validateRules: [
              {
                pattern: /[1-9]+[0-9]*/,
                message: '${title}必须大于0',
              },
              {
                required: true,
                message: '${title}必须大于0',
              },
            ],
          },
          {
            title: '操作',
            width: '10%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      disabled: false,
      selectRowKeys: [],
    }
  },
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
    Examine,
    tableSelect,
  },
  methods: {
    // 编号下拉改弹窗
    openIt() {
      let par = {
        list: '/mess/messProductOrder/list?statusListStr=notStarted,inProduction',
        visible: true, //弹窗开启
        title: '编号', //标题名称
        multi: false, //是否多选
        columns: this.columns, //表格配置
        value: this.numberValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.numberText, //回显的中文，如：'张三'
        textKey: 'orderCode', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    getSelectValue(id, text, item) {
      if (!id) {
        this.requistionForm.goodsBasicUnitText = ''
        this.requistionForm.orderCode = ''
        this.requistionForm.goodsName = ''
        this.requistionForm.orderId = ''
        this.numberText = ''
        this.numberValue = ''
        this.goodsTable.dataSource = []
        return
      }
      this.indexNumber += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.numberValue = id
      this.numberText = text
      this.selectOrder(id)
    },
    searchResetNumber() {
      this.filterForm.orderCode = ''
      this.filterForm.goodsName = ''
      this.$refs.tableSelect.searchReset()
    },
    searchNumber() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    changeDate(v) {
      this.requistionForm.remedyTime = moment(v).format('YYYY-MM-DD HH:mm')
    },
    selectRowChange(ids) {
      this.selectRowKeys = ids
    },
    inputNum(e, props) {
      let newNum = fourFloatNum(e.target.value)
      // let { values } = this.$refs.materialTable.getValuesSync({ validate: true, rowIds: [props.rowId] })
      // let { planTotalNum, onlyReceivedNum, lockNum, returnNum } = values[0]
      // let quantity = Number(planTotalNum) - Number(onlyReceivedNum) - Number(lockNum) + Number(returnNum)
      // if (Number(newNum) > quantity) {
      //   newNum = quantity
      //   this.$refs.materialTable.setValues([
      //     {
      //       rowKey: props.rowId, // 行的id
      //       values: { // 在这里 values 中的 amount 是你 columns 中配置的 key
      //         'num': newNum,
      //       }
      //     }
      //   ])
      //   this.$antdMessage.error('本次领料量不能大于可领数量！可领数量=计划投料总量-锁定量-已领量+已退料量。')
      //   return
      // }
      this.$refs.materialTable.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 amount 是你 columns 中配置的 key
            num: newNum,
          },
        },
      ])
    },
    handleDeleteGood(props) {
      this.$refs.materialTable.removeRows(props.rowId)
    },
    selectOrder(v) {
      if (!v) {
        return
      }
      let order = this.orderList.find((item) => item.id == v)
      this.requistionForm.orderCode = order.orderCode
      this.requistionForm.orderId = order.id
      this.requistionForm.goodsBasicUnitText = order.goodsBasicUnitText
      this.requistionForm.goodsName = order.goodsName
      API.messRemedyMaterialApplyQueryByOrderId({ orderId: v }).then((res) => {
        if (res.result) {
          this.goodsTable.dataSource = res.result
        }
      })
      console.log(order)
    },
    userFilter(v, row) {
      if (row.length > 0) {
        this.requistionForm.remedyId = row[0].id
      }
      // this.$refs.ruleForm2.clearValidate('remedyId')
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取编辑详情 */
    initForm(querys) {
      this.jkeForm.visible = true
      if (querys && querys.orderId) {
        this.requistionForm.goodsBasicUnitText = querys.goodsBasicUnitText
        this.requistionForm.orderId = querys.orderId
        this.numberValue = querys.orderId
        this.numberText = querys.orderCode
        this.requistionForm.orderCode = querys.orderCode
        this.requistionForm.goodsName = querys.goodsName
        API.messRemedyMaterialApplyQueryByOrderId({ orderId: querys.orderId }).then((res) => {
          if (res.result) {
            this.goodsTable.dataSource = res.result
          }
        })
        this.disabled = true
      }
      productOrderList({ pageSize: '999', statusListStr: 'notStarted,inProduction' }).then((res) => {
        if (res.code == 200) {
          this.orderList = res.result.records
        }
      })
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'MESS_DEVICE' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            deviceCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 获取附件 */
    getFileList(v) {
      this.requistionForm.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.handleSubmit(e)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    handleSubmit(processDataVo) {
      console.log(this.requistionForm)
      let that = this
      let requireds = []
      that.$refs.ruleForm1.validate((valid) => {
        if (valid) {
          requireds.push(true)
        }
      })
      that.$refs.ruleForm2.validate((valid) => {
        if (valid) {
          requireds.push(true)
        }
      })
      that.$refs.ruleForm3.validate((valid) => {
        if (valid) {
          requireds.push(true)
        }
      })
      let { error, values } = that.$refs.materialTable.getValuesSync({ validate: true, rowIds: that.selectRowKeys })
      console.log(error, values)
      if (values.length == 0) {
        that.$antdMessage.error('请先选择补用物料')
        return
      } else {
        if (error == 0 && requireds.length == 3) {
          that.requistionForm.messPlanMaterialApplyDtoList = values
          that.requistionForm.processDataVo = processDataVo
          that.submitLoading = true
          API.messRemedyMaterialApplyAdd(that.requistionForm).then((res) => {
            that.submitLoading = false
            if (res.code == 200) {
              that.$antdMessage.success(res.result)
              that.$emit('refresh')
              that.goBack()
            } else {
              that.$antdMessage.error(res.result)
            }
          })
        }
      }
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 80px);
  overflow-y: scroll;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
.item-wrap {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.item-wrap:nth-of-type(n + 2) {
  margin-top: 40px;
}
.detail-item {
  width: 30%;
}
.bd-line {
  height: 1px;
  background: @greyBorder;
  margin: -12px -40px 24px -40px;
}
.cards-box {
  height: calc(100vh - 80px);
  overflow-y: scroll;
}
</style>
